package com.wwwarehouse.resource_center.fragment.rules;

import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.android.flexbox.FlexboxLayout;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.AdderSubtractorView;
import com.wwwarehouse.common.custom_widget.keyboard.VirtualKeyboardView;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.bean.rules.OperatorTypeBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.RulesEvent;

import java.lang.reflect.Method;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/8/10.
 *         <p/>
 *         设置分配方式
 */

public class SetDistributionModeFragment extends TheParentFragment {
    private static final int GET_ALLOCATE_TACTICS = 1;
    private AdderSubtractorView mTaskNumber;
    private AdderSubtractorView mTaskPreload;
    private VirtualKeyboardView mIntKeyboard; // 数字键盘
    //    private RadioGroup allocate_tactics ;
//    private RadioButton task_average ;
//    private RadioButton task_saturation ;
    private Button confirm_btn;
    private String allocateTactics;
    private ArrayList<OperatorTypeBean> typeBeen;
    private FlexboxLayout allocate_tactics;
    private ArrayList<TextView> mTextList;
    private OperatorTypeBean type;
    private EditText mNumberText;
    private EditText mPreloadText;
    private LinearLayout mLayout;
    private OperatorTypeBean typeBean;

    @Override
    protected int getContentId() {
        mLoadingView.setVisibility(View.VISIBLE);
        return R.layout.fragment_rule_set_distribution_mode;
    }

    @Override
    protected void init(View view) {
        mLayout = findView(view, R.id.ll);
        confirm_btn = findView(view, R.id.confirm_btn);
        mIntKeyboard = findView(view, R.id.number);
        mTaskNumber = findView(view, R.id.task_number);
        mTaskPreload = findView(view, R.id.task_preload);
        allocate_tactics = findView(view, R.id.allocate_tactics);
        mTaskNumber.setDataType(AdderSubtractorView.INT);
        mTaskPreload.setDataType(AdderSubtractorView.INT);
        mIntKeyboard.setOnConfirmListener(new VirtualKeyboardView.OnConfirmListener() {
            @Override
            public void confirm() {
                mIntKeyboard.setVisibility(View.GONE);
            }
        });
        mLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIntKeyboard.getVisibility() == View.VISIBLE) {
                    mIntKeyboard.setVisibility(View.GONE);
                }
            }
        });
        confirm_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isSelectOperator = false;
                if (typeBeen != null) {
                    for (int i = 0; i < typeBeen.size(); i++) {
                        if (typeBeen.get(i).isSelect()) {
                            isSelectOperator = true;
                            type = typeBeen.get(i);
                            break;
                        }
                    }
                }
                if (!isSelectOperator) {
                    toastAtTop("请选择分配方式");
                    return;
                }
                if (mTaskNumber.getIntNumber() == 0) {
                    toastAtTop("当前任务数必须大于0");
                    return;
                }
                EventBus.getDefault().post(new RulesEvent(RulesEvent.RULE_ALLOCATETACTICS, type, mTaskNumber.getIntNumber() + ""));
                popFragment();
            }
        });
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof SetDistributionModeFragment)
            mActivity.setTitle("设置分配方式");
    }

    public void showKeyboardInt(EditText editText) {
        mIntKeyboard.setFocusable(true);
        mIntKeyboard.setFocusableInTouchMode(true);
        mIntKeyboard.setEditText(editText);
        if (mIntKeyboard.getVisibility() != View.VISIBLE) {
            mIntKeyboard.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void loadDatas() {
        Bundle bundle = getArguments();
        typeBean = bundle.getParcelable("data");
    }

    @Override
    public void requestDatas() {
        mTaskNumber.setStyle(2);
        mTaskNumber.setLeastValue(0);
        mTaskNumber.setMaximumValue(999);
        mTaskNumber.setDefaultValue(0);
        mTaskPreload.setStyle(2);
        mTaskPreload.setLeastValue(0);
        mTaskPreload.setMaximumValue(999);
        mTaskPreload.setDefaultValue(20);
        mTextList = new ArrayList<>();
        mNumberText = mTaskNumber.getEditText();
        if (typeBean!=null){
            mNumberText.setText(typeBean.getMaxTaskNum()==null?20+"":typeBean.getMaxTaskNum());
        }
        mPreloadText = mTaskPreload.getEditText();
//        allocate_tactics = findView(view,R.id.allocate_tactics);
//        task_average = findView(view,R.id.task_average);
//        task_saturation = findView(view,R.id.task_saturation);
        hideSystemKeyboard(mNumberText, mPreloadText);
        mNumberText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showKeyboardInt(mNumberText);
            }
        });
        mPreloadText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showKeyboardInt(mPreloadText);
            }
        });
        mPreloadText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                showKeyboardInt(mPreloadText);
            }
        });
        mNumberText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                showKeyboardInt(mNumberText);
            }
        });

        httpPost(ResourceConstant.GET_ALLOCATE_TACTICS, null, GET_ALLOCATE_TACTICS, false, "");
    }


    @Override
    public void onReLoad(int code) {
        httpPost(ResourceConstant.GET_ALLOCATE_TACTICS, null, GET_ALLOCATE_TACTICS, false, "");
    }

    private void hideSystemKeyboard(EditText... mNumber) {
        for (int i = 0; i < mNumber.length; i++) {
            // 设置不调用系统键盘
            if (android.os.Build.VERSION.SDK_INT <= 10) {
                mNumber[i].setInputType(InputType.TYPE_NULL);
            } else {
                mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

                Class<EditText> clazz = EditText.class;
                Method method;

                try {
                    method = clazz.getMethod("setShowSoftInputOnFocus", boolean.class);
                    method.setAccessible(true);
                    method.invoke(mNumber[i], false);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    method = clazz.getMethod("setSoftInputShownOnFocus", boolean.class);
                    method.setAccessible(true);
                    method.invoke(mNumber[i], false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        switch (what) {
            case GET_ALLOCATE_TACTICS:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    typeBeen = (ArrayList<OperatorTypeBean>) JSON.parseArray(commonClass.getData().toString(), OperatorTypeBean.class);
                    for (int i = 0; i < typeBeen.size(); i++) {
                        final TextView tv = new TextView(mActivity);
                        tv.setBackgroundResource(R.drawable.selector_single_select_button);
                        tv.setTextColor(getResources().getColor(R.color.common_color_c1_337cff));
                        tv.setText(typeBeen.get(i).getName());
                        tv.setGravity(Gravity.CENTER);
                        tv.setPadding(ConvertUtils.dip2px(mActivity, 15), 0, ConvertUtils.dip2px(mActivity, 15), 0);
                        FlexboxLayout.LayoutParams params = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        params.setMargins(0, 0, ConvertUtils.dip2px(mActivity, 15), ConvertUtils.dip2px(mActivity, 15));
                        tv.setLayoutParams(params);
                        final int finalI = i;
                        tv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                confirm_btn.setEnabled(true);
                                if (v.isSelected()) {
                                    return;
                                }
                                for (int i1 = 0; i1 < mTextList.size(); i1++) {
                                    if ((mTextList.get(i1)).isSelected()) {
                                        mTextList.get(i1).setSelected(false);
                                        mTextList.get(i1).setTextColor(getResources().getColor(R.color.common_color_c1_337cff));
                                    }
                                }
                                for (int i1 = 0; i1 < typeBeen.size(); i1++) {
                                    typeBeen.get(i1).setSelect(false);
                                }
                                typeBeen.get(finalI).setSelect(true);
                                tv.setSelected(true);
                                tv.setTextColor(getResources().getColor(R.color.white));

                            }
                        });
                        allocate_tactics.addView(tv);
                        mTextList.add(tv);
                        if (typeBean!=null&&typeBeen.get(i).getCode().equals(typeBean.getCode())){
                            confirm_btn.setEnabled(true);
                            typeBeen.get(i).setSelect(true);
                            tv.setSelected(true);
                            tv.setTextColor(getResources().getColor(R.color.white));
                        }
                    }
                } else {
                    toastAtTop(commonClass.getMsg());
                }

                break;
        }
    }
}
